package com.szgr.baoyin.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.MyForumListAdapter;
import com.szgr.baoyin.model.ForumCategory;
import com.szgr.baoyin.model.ForumListItem;
import com.szgr.baoyin.myview.CircleImageView;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.DialogUtils;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 我的论坛
 */
public class MyForumActivity extends BaseActivity implements AdapterView.OnItemClickListener, RadioGroup.OnCheckedChangeListener, AbsListView.OnScrollListener {

    private RadioButton rb_left;
    private RadioButton rb_center;
    private RadioButton rb_right;
    private List<ForumCategory> categories;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 400:
                    if(categories != null){
                        MyApplication.getmInstance().setCategories(categories);
                        rb_left.setText(categories.get(0).getBoard_name());
                        rb_center.setText(categories.get(1).getBoard_name());
                        rb_right.setText(categories.get(2).getBoard_name());
                        ForumCategory forumCategory = categories.get(0);
                        board_id = forumCategory.getBoard_id();
                        getForumList(forumCategory.getBoard_id(), "1");
                    }
                    break;
                case 500:
                    DialogUtils.hideLoadingDialog();
                    forumListAdapter.setData(data);
                    break;
                case 600:
                    Map<String,String> map = (Map<String, String>) msg.obj;
                    MyTool.showPicture(MyForumActivity.this,headView,map.get("avatar"));
                    tv_id.setText(map.get("userName"));
                    getMyMessage(map.get("token"),map.get("secret"),map.get("uid"));
                    break;
                case 700:
                    Map<String,String> map1 = (Map<String, String>) msg.obj;
                    tv_level.setText(map1.get("level"));
                    tv_num.setText(map1.get("topic_num"));
                    break;
                case 800:
                    DialogUtils.hideLoadingDialog();
                    break;
            }
        }
    };

    private int currentPage = 1;
    private int pageSize = 10;
    private List<ForumListItem> data;
    private MyForumListAdapter forumListAdapter;
    private ListView forumListView;
    private String board_id;
    private CircleImageView headView;
    private TextView tv_id;
    private TextView tv_level;
    private TextView tv_num;
    private RequestQueue mRequestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_my_forum);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("我的论坛");
    }

    @Override
    public void initView() {
        mRequestQueue = Volley.newRequestQueue(this);
        data = new ArrayList<>();
        forumListView = (ListView) findViewById(R.id.forum_list_view);
        forumListAdapter = new MyForumListAdapter(this, data);
        forumListView.setAdapter(forumListAdapter);
        forumListView.setOnItemClickListener(this);
        forumListView.setOnScrollListener(this);
        TextView tv_send = (TextView) findViewById(R.id.my_forum_send_topic);
        tv_send.setOnClickListener(this);

        headView = (CircleImageView) findViewById(R.id.forum_lz_head_view);
        tv_id = (TextView) findViewById(R.id.forum_id);
        tv_level = (TextView) findViewById(R.id.forum_level);
        tv_num = (TextView) findViewById(R.id.forum_num);

        RadioGroup rg_forum = (RadioGroup) findViewById(R.id.forum_radio_group);
        rg_forum.setOnCheckedChangeListener(this);
        rb_left = (RadioButton) findViewById(R.id.forum_left_btn);
        rb_center = (RadioButton) findViewById(R.id.forum_center_btn);
        rb_right = (RadioButton) findViewById(R.id.forum_right_btn);


        categories = MyApplication.getmInstance().getCategories();
        if(categories != null){
            rb_left.setText(categories.get(0).getBoard_name());
            rb_center.setText(categories.get(1).getBoard_name());
            rb_right.setText(categories.get(2).getBoard_name());
        }else {
            getCategory();
        }
        rb_left.setChecked(true);

        loginForum();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void getMyMessage(final String token, final String secret, final String uid) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_FORUM_MESSAGE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("----message---->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject head = jsonObject.getJSONObject("head");
                            String errCode = head.getString("errCode");
                            if("00000000".equals(errCode)){
                                String topic_num = jsonObject.getString("topic_num");
                                String level = jsonObject.getString("level");
                                Map<String,String> map = new HashMap<>();
                                map.put("topic_num",topic_num);
                                map.put("level",level);
                                mHandler.obtainMessage(700,map).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("accessToken",token);
                map.put("accessSecret",secret);
                map.put("uid",uid);
                return map;
            }
        };
//        MyApplication.getmInstance().addToRequestQueue(sr);
        mRequestQueue.add(sr);
    }

    private void loginForum() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_LOGIN_FORUM,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---login forum-->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject head = jsonObject.getJSONObject("head");
                            String errCode = head.getString("errCode");
                            if("00000000".equals(errCode)){
                                String token = jsonObject.getString("token");
                                String secret = jsonObject.getString("secret");
                                MyApplication.getmInstance().setToken(token);
                                MyApplication.getmInstance().setSecret(secret);
                                String avatar = jsonObject.getString("avatar");
                                String userName = jsonObject.getString("userName");
                                String uid = jsonObject.getString("uid");
                                Map<String,String> map = new HashMap<>();
                                map.put("token",token);
                                map.put("secret",secret);
                                map.put("avatar",avatar);
                                map.put("userName",userName);
                                map.put("uid",uid);
                                mHandler.obtainMessage(600,map).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("type","login");
                map.put("username", MyApplication.getmInstance().getUserPhone());//MyApplication.getmInstance().getUsername()
                map.put("password", MyApplication.getmInstance().getPassword());//MyApplication.getmInstance().getPassword()
                System.out.println("---params--->" + map.toString());
                return map;
            }
        };
//        MyApplication.getmInstance().addToRequestQueue(sr);
        mRequestQueue.add(sr);
    }

    private void getCategory() {
        StringRequest sr = new StringRequest(Request.Method.GET, Constant.URL_FORUM_CATEGORY,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject head = jsonObject.getJSONObject("head");
                            String errCode = head.getString("errCode");
                            if("00000000".equals(errCode)){
                                JSONArray list = jsonObject.getJSONArray("list");
                                for (int i = 0; i < list.length(); i++) {
                                    JSONObject jsonObject1 = list.getJSONObject(i);
                                    JSONArray board_list = jsonObject1.getJSONArray("board_list");
                                    Gson gson = new Gson();
                                    categories = gson.fromJson(board_list.toString(),new TypeToken<List<ForumCategory>>(){}.getType());
                                    mHandler.obtainMessage(400).sendToTarget();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
//        MyApplication.getmInstance().addToRequestQueue(sr);
        mRequestQueue.add(sr);
    }

    private void changeTextColor(RadioButton rb1, RadioButton rb2, RadioButton rb3) {
        rb1.setTextColor(0xffffffff);
        rb2.setTextColor(0xff234b64);
        rb3.setTextColor(0xff234b64);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.my_forum_send_topic:
                if(board_id != null) {
                    if(MyApplication.getmInstance().isLogin()) {
                        Intent topicIntent = new Intent(this, QuestionActivity.class);
                        topicIntent.putExtra("board_id", board_id);
                        startActivityForResult(topicIntent, 77);
                    }else{
                        ToastUtils.showToast("论坛登录失败，退出后重试");
                    }
                }
                break;
            case R.id.item_forum_head_view:
                int tag = (int) v.getTag();
                ForumListItem forumListItem = data.get(tag);
                Intent intent = new Intent(this,BigPictureActivity.class);
                intent.putExtra("url",forumListItem.getUserAvatar());
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if(intent != null){
            switch (resultCode){
                case 98:
                    currentPage = 1;
                    data.clear();
                    getForumList(board_id, "1");
                    break;
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ForumListItem forumListItem = data.get(position);
        Intent intent = new Intent(this, ForumDetailActivity.class);
        intent.putExtra("forumListItem", forumListItem);
        startActivity(intent);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.forum_left_btn:
                changeTextColor(rb_left,rb_center,rb_right);
                currentPage = 1;
                data.clear();
                if(categories != null) {
                    ForumCategory forumCategory = categories.get(0);
                    board_id = forumCategory.getBoard_id();
                    getForumList(board_id, "1");
                }
                break;
            case R.id.forum_center_btn:
                changeTextColor(rb_center,rb_left,rb_right);
                currentPage = 1;
                data.clear();
                if(categories != null) {
                    ForumCategory forumCategory = categories.get(1);
                    board_id = forumCategory.getBoard_id();
                    getForumList(board_id, "1");
                }
                break;
            case R.id.forum_right_btn:
                changeTextColor(rb_right,rb_center,rb_left);
                currentPage = 1;
                data.clear();
                if(categories != null) {
                    ForumCategory forumCategory = categories.get(2);
                    board_id = forumCategory.getBoard_id();
                    getForumList(board_id, "1");
                }
                break;
        }
    }

    private void getForumList(final String board_id, final String order) {
        DialogUtils.showLoadingDialog(this,"正在加载中...");
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_FORUM_LIST,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("-------->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject head = jsonObject.getJSONObject("head");
                            String errCode = head.getString("errCode");
                            if("00000000".equals(errCode)){
                                JSONArray list = jsonObject.getJSONArray("list");
                                Gson gson = new Gson();
                                List<ForumListItem> forumListItems = gson.fromJson(list.toString(),new TypeToken<List<ForumListItem>>(){}.getType());
                                if(forumListItems != null && forumListItems.size() > 0) {
                                    data.addAll(forumListItems);
                                    currentPage++;
                                    mHandler.obtainMessage(500).sendToTarget();
                                }else{
                                    mHandler.obtainMessage(800).sendToTarget();
                                    ToastUtils.showToast("没有更多内容了");
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("boardId",board_id);
                map.put("page",currentPage + "");
                map.put("pageSize",pageSize + "");
                map.put("topOrder",order);
                return map;
            }
        };
//        MyApplication.getmInstance().addToRequestQueue(sr);
        mRequestQueue.add(sr);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if(scrollState == SCROLL_STATE_IDLE){
            if(forumListView.getLastVisiblePosition() == forumListView.getCount() - 1){
                getForumList(board_id,"1");
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
